/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.colswe.testingProject.view;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Collection;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import org.colswe.testingProject.control.ApplicationControl;
import org.colswe.testingProject.control.ApplicationTypeControl;
import org.colswe.testingProject.control.ProgramControl;
import org.colswe.testingProject.entity.Application;
import org.colswe.testingProject.entity.ApplicationType;
import org.colswe.testingProject.entity.Program;

/**
 *
 * @author andres
 */
public class ApplicationSearch extends javax.swing.JPanel {
    
    private final String SELECT_ONE = "Seleccione uno";

    /**
     * Creates new form ApplicationSearch
     */
    public ApplicationSearch() {
        initComponents();
    }
    
    private TableModel generateModel(Collection<Application> applications) {
        String data[][] = null;
        String[] columns = {"Id", "Tipo", "Fecha", "Periodo", "Estado"};
        if (applications.size() > 0) {
            DateFormat dateFormatter = DateFormat.getDateInstance(DateFormat.SHORT, DateFormat.getAvailableLocales()[0]);
            data = new String[applications.size()][5];
            int i = 0;
            for (Application ap : applications) {
                data[i][0] = "" + ap.getId();
                data[i][1] = ap.getType().getName();
                data[i][2] = dateFormatter.format(ap.getDateLastChange());
                data[i][3] = ap.getPeriodApplication();
                data[i][4] = ap.getInstance() + "-" + ap.getDecision();
                i++;
            }
            return new DefaultTableModel(data, columns);
        } else {
            errorMessage("No se encontraron resultados");
            return new DefaultTableModel(data, columns);
        }
    }
    
    private ComboBoxModel generateModelProgram() {
        Collection<Program> programs = new ProgramControl().readAll();
        String[] data;
        data = new String[programs.size() + 1];
        data[0] = SELECT_ONE;
        int i = 1;
        for (Program pr : programs) {
            data[i] = pr.getName();
            i++;
        }
        return new DefaultComboBoxModel(data);
    }
    
    private ComboBoxModel generateModelApplicationType() {
        Collection<ApplicationType> types = new ApplicationTypeControl().readAll();
        String[] data;
        data = new String[types.size() + 1];
        data[0] = SELECT_ONE;
        int i = 1;
        for (ApplicationType ap : types) {
            data[i] = ap.getName();
            i++;
        }
        return new DefaultComboBoxModel(data);
    }
    
    private ComboBoxModel generateModelState() {
        String[] data = new String[]{SELECT_ONE, "En coordinación curricular-Sin Decisión",
            "En reunión del Comité-Aprobada",
            "En reunión del Comité-No Aprobada",
            "En reunión del Comité-Pendiente",
            "En Acta de Consejo-Aprobada",
            "En Acta de Consejo-No Aprobada",
            "En Acta de Consejo-Pendiente"};
        return new DefaultComboBoxModel(data);
    }
    
    private void errorMessage(String message) {
        JOptionPane.showMessageDialog(this, message, "Error", JOptionPane.ERROR_MESSAGE);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        txtId = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        cmbProgram = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();
        cmbType = new javax.swing.JComboBox();
        jLabel4 = new javax.swing.JLabel();
        txtIdNumber = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        txtPeriod1 = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        txtPeriod2 = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        cmbState = new javax.swing.JComboBox();
        btnFilter = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblApplications = new javax.swing.JTable();

        setMaximumSize(new java.awt.Dimension(730, 650));
        setMinimumSize(new java.awt.Dimension(730, 650));

        jLabel1.setText("ID");
        jLabel1.setFocusable(false);

        jLabel2.setText("Programa");
        jLabel2.setFocusable(false);

        cmbProgram.setModel(generateModelProgram());

        jLabel3.setText("Tipo");
        jLabel3.setFocusable(false);

        cmbType.setModel(generateModelApplicationType());

        jLabel4.setText("Cédula");
        jLabel4.setFocusable(false);

        jLabel5.setText("Periodo");
        jLabel5.setFocusable(false);

        jLabel6.setText("-");
        jLabel6.setFocusable(false);

        jLabel7.setText("Estado");
        jLabel7.setFocusable(false);

        cmbState.setModel(generateModelState());

        btnFilter.setText("Filtrar");
        btnFilter.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnFilterActionPerformed(evt);
            }
        });

        jScrollPane1.setViewportView(tblApplications);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtId, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cmbProgram, javax.swing.GroupLayout.PREFERRED_SIZE, 202, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(txtIdNumber, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel3)
                                .addGap(3, 3, 3)
                                .addComponent(cmbType, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addGap(94, 94, 94))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel5)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtPeriod1, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel6)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtPeriod2, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(3, 3, 3)
                                .addComponent(jLabel7)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(cmbState, javax.swing.GroupLayout.PREFERRED_SIZE, 370, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(btnFilter))
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(jScrollPane1))
                .addContainerGap(59, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2)
                    .addComponent(cmbProgram, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4)
                    .addComponent(txtIdNumber, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(cmbType, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(txtPeriod1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6)
                    .addComponent(txtPeriod2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel7)
                    .addComponent(cmbState, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnFilter)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 402, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(94, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void btnFilterActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFilterActionPerformed
        Long id;
        String idNumber, period1 = null, period2, program, type, state;
        ArrayList<String> queries = new ArrayList<String>();
        try {
            if (txtId.getText().length() > 0) {
                id = Long.parseLong(txtId.getText());
                if (id < 0 || id > Integer.MAX_VALUE) {
                    throw new Exception("El número debe ser positivo y menor que " + Integer.MAX_VALUE);
                }
                queries.add("u.id=" + id);
            }
            if (txtIdNumber.getText().length() > 0) {
                idNumber = txtIdNumber.getText();
                try {
                    Long.parseLong(idNumber);
                } catch (NumberFormatException ex) {
                    ex.printStackTrace(System.err);
                    errorMessage("El campo cédula debe ser numérico");
                }
                if (idNumber.length() < 6 || idNumber.length() > 12) {
                    throw new Exception("La cédula debe tener entre 6 y 12 caracteres");
                }
                queries.add("u.student.idNumber='" + idNumber + "'");
            }
            if (txtPeriod1.getText().length() > 0 && txtPeriod2.getText().length() == 0) {
                throw new Exception("El periodo debe ser del formato AAAA-S");
            }
            if (txtPeriod1.getText().length() == 0 && txtPeriod2.getText().length() > 0) {
                throw new Exception("El periodo debe ser del formato AAAA-S");
            }
            if (txtPeriod1.getText().length() > 0) {
                period1 = txtPeriod1.getText();
                try {
                    Integer.parseInt(period1);
                } catch (NumberFormatException ex) {
                    ex.printStackTrace(System.err);
                    errorMessage("El periodo debe ser numérico");
                }
                if (period1.length() != 4) {
                    throw new Exception("El periodo debe ser del formato AAAA-S");
                }
            }
            if (txtPeriod2.getText().length() > 0) {
                period2 = txtPeriod2.getText();
                try {
                    Integer.parseInt(period2);
                } catch (NumberFormatException ex) {
                    ex.printStackTrace(System.err);
                    errorMessage("El periodo debe ser numérico");
                }
                if (period2.length() != 1) {
                    throw new Exception("El periodo debe ser del formato AAAA-S");
                }
                queries.add("u.periodApplication='" + period1 + "-" + period2 + "'");
            }
            program = (String) cmbProgram.getSelectedItem();
            if (!program.equals(SELECT_ONE)) {
                queries.add("u.student.program.name='" + program + "'");
            }
            type = (String) cmbType.getSelectedItem();
            if (!type.equals(SELECT_ONE)) {
                queries.add("u.type.name='" + type + "'");
            }
            state = (String) cmbState.getSelectedItem();
            if (state.equals("En coordinación curricular-Sin Decisión")) {
                queries.add("u.instance='En coordinación curricular' AND u.decision=''");
            }
            if (state.equals("En reunión del Comité-Aprobada")) {
                queries.add("u.instance='En reunión del Comité' AND u.decision='Aprobada'");
            }
            if (state.equals("En reunión del Comité-No Aprobada")) {
                queries.add("u.instance='En reunión del Comité' AND u.decision='No Aprobada'");
            }
            if (state.equals("En reunión del Comité-Pendiente")) {
                queries.add("u.instance='En reunión del Comité' AND u.decision='Pendiente'");
            }
            if (state.equals("En Acta de Consejo-Aprobada")) {
                queries.add("u.instance='En Acta de Consejo' AND u.decision='Aprobada'");
            }
            if (state.equals("En Acta de Consejo-No Aprobada")) {
                queries.add("u.instance='En Acta de Consejo' AND u.decision='No Aprobada'");
            }
            if (state.equals("En Acta de Consejo-Pendiente")) {
                queries.add("u.instance='En Acta de Consejo' AND u.decision='Pendiente'");
            }
        } catch (NumberFormatException ex) {
            ex.printStackTrace(System.err);
            errorMessage("Campo ID no es un número válido");
        } catch (Exception ex) {
            ex.printStackTrace(System.err);
            errorMessage(ex.getMessage());
        }
        if (!queries.isEmpty()) {
            tblApplications.setModel(generateModel(new ApplicationControl().readByFilters(queries)));
        } else {
            tblApplications.setModel(generateModel(new ApplicationControl().readAll()));
        }
    }//GEN-LAST:event_btnFilterActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnFilter;
    private javax.swing.JComboBox cmbProgram;
    private javax.swing.JComboBox cmbState;
    private javax.swing.JComboBox cmbType;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tblApplications;
    private javax.swing.JTextField txtId;
    private javax.swing.JTextField txtIdNumber;
    private javax.swing.JTextField txtPeriod1;
    private javax.swing.JTextField txtPeriod2;
    // End of variables declaration//GEN-END:variables
}
